from StringIO import StringIO
import re
import pdb
import types
from core.ide.datamangager import DataMangager
from core.ide.toolsmanager import ToolsManager
from core.ui.centralpanel import CentralPanel
import os
import subprocess
import cPickle as pickle
import base64
import traceback

PROJECT_PATH=None

RULES={
    package:"package[ \t]+([a-zA-Z0-9_]*)"
}
RULES_ORDER=["class","def","property","var","from","import"]

class CodeReader:
    def __init__(self):
        global PROJECT_PATH
        if ToolsManager().hasTool(ToolsManager().ID_PROJECT):
            project=ToolsManager().getToolById(ToolsManager().ID_PROJECT).getDefaultProject()
            PROJECT_PATH=os.path.abspath(project.getBaseDir())
        
 
        

    def getGlobal(self):
        return self._global

    def read(self,text,path=""):
        self._read(text,path)

    def _read(self,text,path):

        strIO=StringIO(text)
        strIO.seek(0)
        while 1:
            try:
                line= strIO.next()
                self.line+= 1
            except:
                break
            line=line.replace("\n","").replace("\r","")
            ctxt=self.readLine(line)


    def readLine(self,line):
        for name in RULES_ORDER:
            exp=RULES[name].search(line)
            if exp is not None:
                ctxt = getattr(self, "read_" + name)(line,exp)   
        return ctxt
    
    def read_package(self):
        pass
    
    
    
    
class Context(object):
    def __init__(self):
        self.level=0
        self.name=""
        self.ruleName=""
        self.type=None
        self.childs={}
        self.parent=None
        self.typeValue=None
        self.path=""
        self.id=""
        #self.modifer
    
    def getStringTypeValue(self):
        if self.typeValue:
            return self.typeValue
        else:
            return "None"
    
    def read(self,tag,expResult):
        pass
    
    def addChild(self,child):
        self.childs[child.name]=child
        child.parent=self
        
    def getChilds(self):
        return self.childs.values()
    
    def getChild(self,name):
        if self.childs.has_key(name):
            return self.childs[name]
        else:
            return None
        
    def removeChild(self,name):
        del self.childs[name]